<template>
	<gracePage headerBG="#FFFFFF" footerBg="#FFFFFF" :customHeader="false">
		<view slot="gBody" style="padding-bottom:120rpx;">
			<!-- 图 -->
			<swiper v-if="imageNum" class="grace-swiper"  autoplay="true" indicator-dots 
			indicator-color="rgba(255, 255, 255, 1)" indicator-active-color="#3688FF" 
			style="height:399rpx" interval="5000">
				<swiper-item class="grace-swiper-item" v-for="(item, index) in swiperItems" :key="index">
					<image :src="item" mode="aspectFit" class="grace-swiper-image"></image>
				</swiper-item>
			</swiper>
			<!-- 商品标题-->
			<view class="grace-product-padding grace-space-between grace-flex-vcenter">
				<text class="grace-product-title grace-bold">{{object.field3}}</text>
			</view>
			<view class="grace-common-line"></view>
			<!-- 价格 -->
<!-- 			<view class="grace-product-padding">
				<view class="grace-space-between grace-flex-vcenter">
					<text class="grace-text-small grace-gray">课程价格：{{object.field12}}/{{object.field11}}</text>
					<text @tap="buy(object)"><button type="default" class="grace-text-small grace-gray">购买课程</button></text>
				</view>
			</view>
			<view class="grace-common-line"></view> -->
			<view class="grace-product-padding">
				<view class="grace-nowrap grace-flex-vcenter">
					<text class="grace-product-price">￥{{object.field12}}元/{{object.field11}}</text>
					<!-- <text class="grace-text grace-gray grace-line-through" style="margin-left:30rpx;">￥{{product.priceMarket}}</text> -->
				</view>
				<view class="grace-space-between grace-flex-vcenter">
					<!-- <text class="grace-text-small grace-gray">运费 ￥0.00</text> -->
					<text class="grace-text-small grace-gray">电量 {{object.field10}}</text>
					<text class="grace-text-small grace-gray">租借 {{object.field13}}次</text>
					<text @tap="lend"><button type="default" class="grace-text-small grace-gray">{{productionOrderBuyButton}}</button></text>
				</view>
			</view>
			<view class="grace-common-line"></view>
			<!-- 详情切换导航 -->
			<view class="grace-product-padding">
				<graceNavBar :items="navItems" lineHeight="80rpx" :isCenter="true" 
				:currentIndex="active" :size="200" activeLineBg="#FF7900" textAlign="center"
				activeColor="#FF7900" activeLineWidth="200rpx" activeLineHeight="2rpx" 
				:margin="10"></graceNavBar>
			</view>
			<!-- 详情-->
			<view class="grace-product-padding" :hidden="active == 1">
				<image class="grace-product-info-img" :src="item" mode="widthFix" v-for="(item,index) in swiperItems" :key="index"></image>		
				<view class="grace-margin-top">
					<text class="grace-text">{{object.field9}}</text>
				</view>				
			</view>	
		</view>
		<!-- 底部 -->
		<view class="grace-space-between grace-flex-vcenter grace-bg-white" slot="gFooter">
			<view class="grace-grids grace-nowrap" style="width:250rpx;">
				<view class="grace-grids-items grace-relative" @tap="gohome">
					<text class="grace-grids-icon grace-icons icon-home"></text>
					<text class="grace-grids-text grace-grids-text">首页</text>
				</view>
			</view>
			<view class="grace-flex-end" style="width:460rpx;">
				<!-- <button type="warn" class="grace-footer-button" style="background:#F37B1D;" @tap="">偷油演习</button> -->
				<button type="warn" class="grace-footer-button" style="background:#E55D52;" @tap="lend">立即租借</button>
			</view>
		</view>
	</gracePage>
</template>
<script>
import gracePage from "../../graceUI/components/gracePage.vue";
import graceNavBar from "../../graceUI/components/graceNavBar.vue";
import graceNumberBox from '../../graceUI/components/graceNumberBox.vue';
import graceSelectTags from '../../graceUI/components/graceSelectTags.vue';
var _self;
export default {
    data() {
    	return {
			swiperItems : [],
			// 切换导航
			navItems : ['产品详情'],
			active:0,
			object : "",
			days:0,
			objectUserPhone:"",
			onShareTimelineImageUrl:"",
			token:"",
			appInfo:"",
			productionID:"",//课程ID
			imageNum:true,
			userInfoData : "",
			pageNum : 1,
			//每次加载的记录数
			pageSize : 10,
			productionOrderBuyButton : "租借设备",
			productionOrderState:false
		}
    },
	onLoad: async function (e){
		_self = this;
		_self.$myFunction.displayLog("onLoad事件e:"+JSON.stringify(e));
		_self.productionID = e.id;
		//获取token，同步方法
		_self.token =  await _self.$myFunction.getToken();
		_self.token = _self.token.token;
		// 获取详情
		_self.getObjectDetail(_self.productionID);
	},
	onShow:function(e){
		//登录事件触发页面刷新
		uni.$once('loginRefresh',function(data){
			_self.$myFunction.displayLog("loginRefresh事件触发object/detail页面刷新");
			//重置相关参数开始
			// _self.pageNum = 1;
			// _self.loadMoreText = "加载更多";
			// _self.showLoadMore = false;
			// _self.createTimeTo = _self.$myFunction.nowTime('Y-m-d H:i:s');
			// 获取详情
			_self.getObjectDetail(_self.productionID);
		})	
		//支付成功事件触发页面刷新
		uni.$once('paySuccessRefresh',function(data){
			_self.$myFunction.displayLog("paySuccessRefresh事件触发object/detail页面刷新");
			//重置相关参数开始
			// _self.pageNum = 1;
			// _self.loadMoreText = "加载更多";
			// _self.showLoadMore = false;
			// _self.createTimeTo = _self.$myFunction.nowTime('Y-m-d H:i:s');
			// 获取详情
			_self.getObjectDetail(_self.productionID);
		})	
	},	
	//发送给朋友
	onShareAppMessage(res) {
		if (res.from === 'button') {// 来自页面内分享按钮
			return {
			  title: _self.appInfo.field5+" "+res.target.dataset.content,
			  path: "/pages/object/detail?id="+res.target.dataset.id+"&wuLuCode="+_self.wuLuCode	
			}								
		}else{
			return {
			  title: _self.appInfo.field5+" "+_self.object.field1,
			  path: "/pages/object/detail?id="+_self.object.id+"&wuLuCode="+_self.wuLuCode
			}				
		}
	},	
	//分享到朋友圈
    onShareTimeline(res) {
        return {
            title: _self.appInfo.field5+" "+_self.object.field1,
			query: "id="+_self.object.id+"&wuLuCode="+_self.wuLuCode,
            imageUrl: _self.onShareTimelineImageUrl
        }
    },	
	methods:{
		//第二步：获取详情
		getObjectDetail: function(){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
				'id': _self.productionID
			};	
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}		
			//重
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;				
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'productionDetail',
				data: paramsData,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},					
				success: data => {
					_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));
					uni.hideToast();
					if (data.data.code == 200) {
						_self.object = data.data.data.productionDto;
						//图片处理
						// http://10.81.116.209/resource/youXiangWeiShi/productionImage/2001/1.jpg
						//图片1——用于app图标
						// if(!_self.$myFunction.isEmpty(_self.object.field4)){
						// 	_self.swiperItems.push(_self.$myFunction.appConfig().serverIp+"resource/youXiangWeiShi/productionImage/"+_self.object.field1+"/"+_self.object.field4);
						// }
						//图片2
						if(!_self.$myFunction.isEmpty(_self.object.field5)){
							_self.swiperItems.push(_self.$myFunction.appConfig().serverIp+"resource/youXiangWeiShi/productionImage/"+_self.object.field1+"/"+_self.object.field5);
						}
						//图片3
						if(!_self.$myFunction.isEmpty(_self.object.field6)){
							_self.swiperItems.push(_self.$myFunction.appConfig().serverIp+"resource/youXiangWeiShi/productionImage/"+_self.object.field1+"/"+_self.object.field6);
						}
						//图片4
						if(!_self.$myFunction.isEmpty(_self.object.field7)){
							_self.swiperItems.push(_self.$myFunction.appConfig().serverIp+"resource/youXiangWeiShi/productionImage/"+_self.object.field1+"/"+_self.object.field7);
						}
						//图片5
						if(!_self.$myFunction.isEmpty(_self.object.field8)){
							_self.swiperItems.push(_self.$myFunction.appConfig().serverIp+"resource/youXiangWeiShi/productionImage/"+_self.object.field1+"/"+_self.object.field8);
						}			
						//产品详情
						_self.object.field9 = _self.object.field9.replace(/\\n/g,'\n');
						//发布天数
						var startDateTemp = _self.object.createTime.replace(/-/g,'/')   //为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23'	
						var startDate = Date.parse(startDateTemp);
						var endDateTemp = _self.$myFunction.nowTime("Y-m-d H:i:s").replace(/-/g,'/')   //为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23'
						var endDate = Date.parse(endDateTemp);
						_self.days = parseInt((endDate - startDate)/(1*24*60*60*1000)+1);
						//若用户已登录，判断用户是否购买课程
						_self.userInfoData = _self.$myFunction.appStorage('wuLuUserInfo');
						if(!_self.userInfoData){
							_self.$myFunction.displayLog("用户未登录");
						}else{	
							let userPhone = _self.userInfoData.field2;
							_self.getProductionOrder(userPhone);
						}
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/object/detail'
									});
								}
							});
						}else{
							uni.showToast({title: "发生错误，请重试",icon: 'none'});
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
				}					
			});				
		},
		//练习
		//先判断用户是否购买课程（查询当前产品的用户订单情况），未购买时自动跳转到购买界面；
		//支付成功后重新加载当前页码，将【购买课程】按钮显示为【已购买】，点击提示已购买；
		//购买过的用户点击课程练习直接进行课程练习界面
		study:function(){
			_self.userInfoData = _self.$myFunction.appStorage('wuLuUserInfo');
			if(!_self.userInfoData){
				//因此页面是主页面，页面显示完成之后才能进行是否登录判断，延时2秒解决未登录提示一闪而过现象
				uni.showToast({title: '您未登录',icon: 'none'});//默认显示1500毫秒
				setTimeout(function () {
					uni.navigateTo({
						url:"../loginReg/index"
					})	
				}, 1500);
			}else{	
				//是否购买课程
				if(_self.productionOrderState){
					//判断是选项题目还是语音
					if(_self.object.field3.indexOf("ICAO_P1") != -1){
						uni.navigateTo({
							url:"../study/ICAO_P1Topic?id="+_self.productionID
						})
					}else if(_self.object.field3.indexOf("ICAO_P2") != -1){
						uni.navigateTo({
							url:"../study/ICAO_P2Topic?id="+_self.productionID
						})
					}else if(_self.object.field3.indexOf("ICAO_P3") != -1){
						uni.navigateTo({
							url:"../study/ICAO_P3Topic?id="+_self.productionID
						})
					}else if(_self.object.field3.indexOf("ICAO_P4") != -1){
						uni.navigateTo({
							url:"../study/ICAO_P4Topic?id="+_self.productionID
						})
					}else if(_self.object.field3.indexOf("理论大纲") != -1){
						uni.navigateTo({
							url:"../study/liLunDaGangTopic?id="+_self.productionID
						})
					}else{
						uni.navigateTo({
							url:"../study/topic?id="+_self.productionID
						})
					}
					
				}else{
					uni.showToast({title: '您未购买该课程',icon: 'none'});//默认显示1500毫秒
					setTimeout(function () {
						uni.navigateTo({
							url:'../order/add?id='+_self.productionID
						})	
					}, 1500);
				}	
			}
		},
		//租借
		lend:function(){
			_self.userInfoData = _self.$myFunction.appStorage('wuLuUserInfo');
			if(!_self.userInfoData){
				uni.showToast({title: '您未登录',icon: 'none'});//默认显示1500毫秒
				setTimeout(function () {
					uni.navigateTo({
						url:"../loginReg/index"
					})	
				}, 1500);
			}else{
				uni.navigateTo({
					url:'../order/add?id='+_self.productionID
				})
			}	
		},
		call:function(){
			// 选择确认
			uni.showModal({
				title: '提示',
				content: '开始拨打电话？',
				success: function (res) {
					if (res.confirm) {
						uni.makePhoneCall({
							phoneNumber: _self.objectUserPhone
						});							
					} else if (res.cancel) {
						return;
					}
				}
			});				
		},
		// 返回首页
		gohome : function(){
			uni.switchTab({
				url:'../object/index'
			});
		},
		//先判断用户是否购买课程（查询当前产品的用户订单情况），未购买时自动跳转到购买界面；
		//支付成功后重新加载当前页码，将【购买课程】按钮显示为【已购买】，点击提示已购买；
		//购买过的用户点击提示您已购买
		buy : function(){
			_self.userInfoData = _self.$myFunction.appStorage('wuLuUserInfo');
			if(!_self.userInfoData){
				//因此页面是主页面，页面显示完成之后才能进行是否登录判断，延时2秒解决未登录提示一闪而过现象
				uni.showToast({title: '您未登录',icon: 'none'});//默认显示1500毫秒
				setTimeout(function () {
					uni.navigateTo({
						url:"../loginReg/index"
					})	
				}, 1500);
			}else{	
				//是否购买课程
				if(_self.productionOrderState){
					uni.showToast({title: '您已购买过该课程',icon: 'none'});//默认显示1500毫秒
				}else{
					uni.navigateTo({
						url:'../order/add?id='+_self.productionID
					})	
				}	
			}	
		},
		//读取用户订单
		getProductionOrder: function(phone){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
				'field1':'',
				'field2':_self.object.field1,
				'field3':'',
				'field4':'',
				'field5':'',
				'field6':'',
				'field7':'',
				'field8':'',
				'field9':'',
				'field10':'',
				'field11':'',
				'field12':'',
				'field13':'',
				'field14':'',
				'field15':'paySuccess',
				'field16':'',
				'field17':'',
				'field18':phone,
				'field19':'',
				'field20':'',
				'status':"1",
				'createTimeFrom':'',
				'createTimeTo':'',
				'pageNum':_self.pageNum,
				'pageSize':_self.pageSize,
				'order':'desc',
				'field':"createTime"
			};
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;				
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'productionOrderList',
				data: paramsData,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},		
				success: data => {
					// 刷新完毕后关闭刷新
					uni.hideToast();
					_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));					
					if (data.data.code == 200) {
						//总记录数
						var total = data.data.data.total;
						_self.$myFunction.displayLog("服务器返回数据总记录数："+total);
						var objectsData=data.data.data.rows;
						_self.$myFunction.displayLog("服务器返回当前查询条件记录数："+objectsData.length);						
						if(total == 0){//查询到0条记录
							return;
						}else{
							_self.productionOrderBuyButton = "已购买";
							_self.productionOrderState = true;
						}
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/object/detail'
									});
								}
							});
						}else{
							_self.$myFunction.displayLog("列表读取失败："+JSON.stringify(data));
							uni.hideToast();
							uni.showToast({title: '连接失败...',icon: 'none'});
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
				}
			});	
		}
	},
	components:{
		gracePage, 
		graceNavBar, 
		graceSelectTags, 
		graceNumberBox,
	}
}
</script>
<style>
.grace-common-line{height:16rpx;}
.grace-product-padding{padding:20rpx 25rpx;}
.grace-product-title{line-height:44rpx; font-size:medium;}
.grace-product-share{width:80rpx; height:80rpx; text-align:center; font-size:40rpx; color:#FF7900; line-height:80rpx; flex-shrink:0; margin-left:12px;}
.grace-product-share:after{width:0; height:0;}
.grace-product-price{color:#FF7900; line-height:60rpx; font-size:30rpx; font-weight:bold;}
.grace-product-info-img{width:100%;}
.grace-product-attr-info{overflow:hidden; display:flex; justify-content:space-between;  border-bottom:1px solid #F1F1F3; padding-bottom:26rpx;}
.grace-product-attr-info-image{width:120rpx; height:auto; margin-right:10px; flex-shrink:0;}
.grace-product-attr-info-body{width:700rpx;}
.grace-product-attr-info-title{width:100%; font-size:28rpx; color:#333333; display:block;}
.grace-product-attr-info-stone{width:100%; font-size:20rpx; margin-top:8rpx; color:#666666; display:block;}
.icon-close{font-size:30rpx; line-height:80rpx; color:#888888;}
/* 调整宫格大小 */
.grace-grids-items{padding:6rpx 0; width:120rpx;}
.grace-grids-icon{height:50rpx; line-height:50rpx; font-size:40rpx; color:#6B7375;}
.grace-grids-text{line-height:28rpx; font-size:20rpx; margin-top:2px; color:#6B7375;}
.grace-footer-active{color:#FF0036;}

.grace-form-body{width:550rpx;}

/* 文字大小 */
.grace-text{font-size:medium; line-height:70rpx;}
</style>